//对于axios进行二次封装
import axios from 'axios';
axios.defaults.withCredentials = true     //全局设置axios允许携带cookie进行访问   
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';

//引入进度条
import NProgress from 'nprogress';
//引入相应的样式
import 'nprogress/nprogress.css';


//引入路由
import router from '@/router'

//start:进度条开始 done:进度条结束

// 创建axios实例
//service就是axios的实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: '/api',
    // 超时
    timeout: 10000
});

// request拦截器
//请求拦截器:在请求发送之前做一些处理
service.interceptors.request.use((config) => {
    NProgress.start();
    if (config.method === 'get' && config.params) {
        let url = config.url + '?';
        for (const propName of Object.keys(config.params)) {
            const value = config.params[propName];
            var part = encodeURIComponent(propName) + "=";
            if (value !== null && typeof (value) !== "undefined") {
                if (typeof value === 'object') {
                    for (const key of Object.keys(value)) {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        url += subPart + encodeURIComponent(value[key]) + "&";
                    }
                } else {
                    url += part + encodeURIComponent(value) + "&";
                }
            }
        }
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
    }
    return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

//响应拦截器
service.interceptors.response.use((res) => {
    NProgress.done();
    console.log("----响应拦截器----")
    //未设置状态码则默认成功状态
    const code = res.data.code;
    if (res.data.code === 0 && res.data.msg === 'NOTLOGIN') {// 返回登录页面
        console.log('---未登录---')
        localStorage.removeItem('userInfo')
        router.push('/login')
    } else {
        return res.data
    }
}, error => {
    let { message } = error;
    if (message == "Network Error") {
        message = "后端接口连接异常,请启动后端程序";
    } else if (message.includes("timeout")) {
        message = "请求超时啦";
    } else if (message.includes("Request failed with status code")) {
        message = "恭喜您,系统接口" + message.substr(message.length - 3) + "异常";
    }
    window.ELEMENT.Message({
        message: message,
        type: 'error',
        duration: 5 * 1000
    })
    return Promise.reject(error)

});

export default service;